<?php

namespace App\Common\SDK\Domain;

use Illuminate\Support\Facades\Cache;

class BaiDu extends Base
{
    public function auth($apiKey, $secretKey)
    {
        return Cache::remember(
                'BAIDU_ACCESS_TOKEN_APP_KEY_' . $apiKey,
                29 * 86400, // 一般是 30 天的有效期,这里 29 天缓存过期
                fn() => $this->request(Base::METHOD_GET, 'oauth/2.0/token', [
                    'grant_type' => 'client_credentials',
                    'client_id' => $apiKey,
                    'client_secret' => $secretKey,
                ]))['access_token'] ?? '';
    }

    protected function requestAfter($response)
    {
        return json_decode($response, true);
    }

    public function address($text, $options = [])
    {
        $data = [
            'text' => $text,
        ];
        $data = array_merge($data, $options);

        return $this->request(Base::METHOD_POST, 'rpc/2.0/nlp/v1/address?' . http_build_query([
                'access_token' => $this->auth(env('BAI_DU_NLP_APPID'), env('BAI_DU_NLP_SECRET')),
                'aipSdk' => 'php',
                'aipSdkVersion' => '2_2_19'
            ]), $data, Base::FORMATTED_DATA_TYPE_JSON);
    }
}
